﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;

namespace DingChiServiceApp.helper
{
    public static class LogHelper
    {
        public static List<LogInfo> _logs;
        public static List<LogInfo> Logs
        {
            get
            {
                if (_logs == null)
                {
                    _logs = new List<LogInfo>();
                }
                if (_logs.Count <= 0)
                {
                    _logs = ReaderFromFile();
                }
                return _logs;
            }
        }

        public static int id;

        /// <summary>
        /// 将日志信息保存到 运行时根目录下的/log/log当天日期.txt
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isError">是否是错误</param>
        public static void FileLog(string msg, bool isError = false)
        {
            if (String.IsNullOrEmpty(msg))
            {
                return;
            }
            string currentDate = DateTime.Now.ToString("yyyy-MM-dd ");
            msg = DateTime.Now.ToString(" hh:mm:ss") + "---------> \t" + msg + "\r\n";
            string root = AppDomain.CurrentDomain.BaseDirectory.ToString();
            string path = Path.Combine(root, "log");

            Logs.Add(new LogInfo(msg, isError ? 1 : 0));

            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            string fileName = path + "\\" + "log_" + currentDate + ".txt";

            if (!File.Exists(fileName))
            {
                File.Create(fileName);
            }
            try
            {
                WriteAppend(fileName, msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("write log error:" + ex.Message);
            }
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        public static void WriteAppend(string path, string content)
        {
            using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
            {
                fs.Position = fs.Length;
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.BaseStream.Seek(0, SeekOrigin.End);
                    writer.Write(content);
                    writer.Flush();
                }
            }
        }


        public class LogInfo
        {
            public LogInfo(string msg, int errLevel)
            {
                LogHelper.id++;
                this.id = LogHelper.id + 1;
                this.msg = msg;
                this.errLevel = errLevel;
            }
            public int id = 0;
            public string msg;
            public int errLevel;
        }

        private static List<LogInfo> ReaderFromFile()
        {
            List<LogInfo> list = new List<LogInfo>();

            string currentDate = DateTime.Now.ToString("yyyy-MM-dd ");
            string root = AppDomain.CurrentDomain.BaseDirectory.ToString();
            string path = Path.Combine(root, "log");
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            string fileName = path + "\\" + "log_" + currentDate + ".txt";

            if (!File.Exists(fileName))
            {
                string info = $"{fileName} 文件不存在，可能服务未启动。";
                return new List<LogInfo>() { new LogInfo(info, 1) };
            }
            string[] strs = File.ReadAllLines(fileName);

            foreach (string str in strs)
            {
                if (string.IsNullOrEmpty(str) || str.Length < 8)
                {
                    continue;
                }
                list.Add(new LogInfo(str, 0));
            }
            return list;
        }
    }
}
